{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-08-06T09:04:06.202874Z",
     "start_time": "2024-08-06T09:04:05.436564Z"
    }
   },
   "source": [
    "from langchain_core.tools import tool  \n",
    "from langchain.pydantic_v1 import BaseModel, Field\n",
    "from langchain_core.tools import render_text_description\n",
    "from langchain.agents import AgentExecutor, create_react_agent\n",
    "from langchain import hub\n",
    "from langchain_community.chat_models import ChatOllama\n",
    "\n",
    "# ============================================================\n",
    "# 自定义工具\n",
    "# ============================================================\n",
    "class SearchInput(BaseModel):\n",
    "    location: str = Field(description=\"location to search for\")  # 定义一个 Pydantic 模型，用于描述输入模式，并提供描述信息\n",
    "\n",
    "@tool(args_schema=SearchInput)\n",
    "def weather_forecast(location: str):\n",
    "    \"\"\"天气预报工具。\"\"\"\n",
    "    print(f\"Weather for {location}\")  # 打印要预报天气的位置\n",
    "    return f\"A dummy forecast for {location}.\"  # 返回给定位置的虚拟天气预报"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-06T09:04:12.527130Z",
     "start_time": "2024-08-06T09:04:06.202874Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 测试不加工具\n",
    "llm = ChatOllama(model=\"gemma:2b\")  # 初始化 ChatOllama 模型，使用 \"gemma:2b\"\n",
    "llm.invoke(\"What is the weather in Paris?\").content "
   ],
   "id": "73a424092ac0a89a",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'I do not have access to real-time information and cannot provide weather updates. For the most up-to-date weather information, I recommend checking a weather app or website such as the National Weather Service (NWS) or the European Central Weather Agency (ECWA).'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-06T09:04:33.367487Z",
     "start_time": "2024-08-06T09:04:12.527130Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 测试使用工具\n",
    "tools = [weather_forecast]  # 使用 weather_forecast 工具\n",
    "prompt = hub.pull(\"hwchase17/react-json\")  # 从 hub 拉取特定提示\n",
    "prompt = prompt.partial(\n",
    "    tools=render_text_description(tools),  # 为提示呈现工具的文本描述\n",
    "    tool_names=\", \".join([t.name for t in tools]),  # 将工具名称连接成一个以逗号分隔的字符串\n",
    ")\n",
    "agent = create_react_agent(llm, tools, prompt)  # 使用 llm、工具和自定义提示创建代理\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, handle_parsing_errors=True, verbose=False, format=\"json\")  # 使用指定参数初始化 AgentExecutor\n",
    "print(agent_executor.invoke({\"input\":\"What is the weather in Paris?\"}))  # 使用测试输入调用代理并打印结果"
   ],
   "id": "d8ba4157f75da004",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'input': 'What is the weather in Paris?', 'output': '** 68.2°F (20.1°C) with a 60% chance of rain'}\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-06T09:04:50.480641Z",
     "start_time": "2024-08-06T09:04:33.368490Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 使用对话历史\n",
    "# 拉去特定提示，注意此处使用的是 react-chat\n",
    "prompt = hub.pull(\"hwchase17/react-chat\")\n",
    "\n",
    "# 构建 ReAct agent\n",
    "agent_history = create_react_agent(llm, tools, prompt)\n",
    "agent_executor = AgentExecutor(agent=agent_history, tools=tools, verbose=False)\n",
    "\n",
    "agent_executor.invoke(\n",
    "    {\n",
    "        \"input\": \"what's my name? Only use a tool if needed, otherwise respond with Final Answer\",\n",
    "        \"chat_history\": \"Human: Hi! My name is Bob\\nAI: Hello Bob! Nice to meet you\",\n",
    "    }\n",
    ")"
   ],
   "id": "ddc0579b230549aa",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'input': \"what's my name? Only use a tool if needed, otherwise respond with Final Answer\",\n",
       " 'chat_history': 'Human: Hi! My name is Bob\\nAI: Hello Bob! Nice to meet you',\n",
       " 'output': '** Your name is Bob.'}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 4
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
